/**
 * postcss-px2vw插件
 * @param {{viewportWidth?: number, unitPrecision?: number, minPixelValue?: number}} opts 
 * @returns 
 */
export default function (opts = {}) {
    // 默认选项
    const options = Object.assign(
        {
            viewportWidth: 750, // 设计稿宽度，默认750vw
            unitPrecision: 5, // 保留小数位数
            minPixelValue: 1, // 最小转换值
        },
        opts,
    )

    return {
        postcssPlugin: 'postcss-px2vw',
        Declaration(decl) {
            if (decl.value.includes('px')) {
                decl.value = decl.value.replace(/(\d*\.?\d+)px/g, (match, size) => {
                    if (parseFloat(size) <= options.minPixelValue) return match
                    const vwValue = (parseFloat(size) / options.viewportWidth) * 100
                    return `${vwValue.toFixed(options.unitPrecision)}vw`
                })
            }
        },
    }
}
